import Api from "@/api/api-declare";
import { DRIVER_RATE_LEVEL, type ORDER_CHANNEL } from "../enum/pd-enum";
import type { ApiDriverStatTypes } from "@/api/api-types/api-driver-stat-types";

//完单统计
export function useDataBoard() {
	/**
	 * 统计数据
	 */
	const statData = ref<ApiDriverStatTypes.GetDataBoardRes>({
		complete : {},
		uncomplete : -1,
		avg_rate : 0,
		complete_num : 0,
		month_accept_num: 0,
		month_close_num: 0,
		total_rate_color: "#05BE74",
		total_rate_text: "暂无",
	});

	/**
	 * 渠道列表
	 */
	const channels = ref<Array<{channel_id : number | string, name : string}>>([
		{
			channel_id : '',
			name : '顺风车完单率'
		}
	]);

	/**
	 * 获取完单率数据统计
	 * @param {number} channel_id 渠道id
	 * @param {boolean} force 是否强制从服务端拉取最新数据 
	 */
	const getDataBoard = (channel_id : ORDER_CHANNEL | string,force = false): Promise<void> => {
		return new Promise((r) => {
			if (!force && statData.value.uncomplete !== -1) {
				r();
			};
			Api.ApiDriverStat.getDataBoard({channel_id}).then(res => {
				statData.value = res.order;
				//构造数据统计可筛选渠道列表
				if (Object.keys(res.order.complete).length && channels.value.length <= 1) {
					channels.value = [
						...channels.value,
						...Object.keys(res.order.complete).map(v => {
							return {
								channel_id : Number(v),
								name : res.order.complete[v].name
							};
						})
					];
				};
				r();
			});
		});
	};

	/**
	 * 获取完单率等级
	 * @param {number} value 
	 * @returns {DRIVER_RATE_LEVEL} 完单率等级
	 */
	const getRateLevel = (value : number) => {
		return value >= 70 ? DRIVER_RATE_LEVEL.high : (value < 50 ? DRIVER_RATE_LEVEL.low : DRIVER_RATE_LEVEL.middle);
	};



	return {
		statData,
		channels,
		getDataBoard,
		getRateLevel
	};
}